﻿using DMSkin.Core;
using Dt261.Base;
using Dt261.Model;
using Dt261.ViewModel;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Dt261.Views
{
    /// <summary>
    /// TestWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestWindow 

    {
        private Collection<string> hzs = new Collection<string> { "125", "250", "500", "1K", "2K", "4K", "8K" };
        private Collection<int> hzsint = new Collection<int> { 125, 250, 500,750, 1000,1500, 2000,3000, 4000,6000, 8000 };

        Dictionary<int, double> hzsPxValue = new Dictionary<int, double> { { 125, 0 }, { 250, 1 }, { 500, 2 },{ 750, 2.5 }, { 1000, 3 }, { 1500, 3.5 }, { 2000, 4 },
            { 3000, 4.5 }, { 4000, 5 },{ 6000, 5.5 }, { 8000, 6 } };
        //Dictionary<int, int> limitHz = new Dictionary<int, int> { { 125, 65 }, { 250, 85 }, { 500, 105 },{ 750, 105 },  { 1000, 105 }, { 1500, 105 }, { 2000, 105 },
        //    { 3000, 105 }, { 4000, 105 },{ 6000, 100 }, { 8000, 95 } };
        //Dictionary<int, int> limitGuDaoHz = new Dictionary<int, int> { { 125, -10 }, { 250, 45 }, { 500, 60 },{ 750, 60 },  { 1000, 70 }, { 1500, 70 }, { 2000, 70 },
        //    { 3000, 70 }, { 4000, 60 },{ 6000, -10 }, { 8000, -10 } };
        private int topM = 45;
        private int rightM = 80;
        private double px;
        private double py;

        private bool tishiquit = true;

        private List<Point> dataPoints = new List<Point>();
        private PointCollection coordinatePoints = new PointCollection();
        private List<Shape> pointEllipses = new List<Shape>();
        private List<Shape> pointEllipses2 = new List<Shape>();//

        private List<Shape> pointEllipses3 = new List<Shape>();//十字线 掩蔽点

        private List<Shape> pointBcEllipses = new List<Shape>();
        private List<Shape> pointBcEllipses2 = new List<Shape>();//


        Polyline curvePolyline = new Polyline();


        private Point yuandian = new Point(40,305);
        public TestWindow()
        {
            InitializeComponent();
            initData(null);
            
        }

        public TestWindow(MemberInfo m)
        {
            InitializeComponent();
            initData(m);

        }


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

            if(this.tishiquit)
            {
                var result = MessageBoxX.Show("确认退出听力测试？", "提醒", Window.GetWindow(chartCanvas), MessageBoxButton.YesNo, new MessageBoxXConfigurations()
                {
                    MessageBoxStyle = MessageBoxStyle.Modern,
                    MessageBoxIcon = MessageBoxIcon.Warning,
                    ButtonBrush = "#F1C825".ToColor().ToBrush(),
                });

                //MessageBoxResult result = MessageBox.Show("确认退出听力测试？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {

                    e.Cancel = false;

                    TestWindowViewModel m = DataContext as TestWindowViewModel;


                    m.Dispose();

                    this.UninstallBroadcast();


                }


                //不关闭窗口
                if (result == MessageBoxResult.No)
                    e.Cancel = true;
            }
            else
            {
                e.Cancel = false;

                TestWindowViewModel m = DataContext as TestWindowViewModel;


                m.Dispose();
                this.UninstallBroadcast();
            }


        }

        private void UninstallBroadcast()
        {
            DMSkin.Core.Broadcast.UninstallBroadcast("NEWTESTDATA");
            DMSkin.Core.Broadcast.UninstallBroadcast("CLOSEWINDOW");
            DMSkin.Core.Broadcast.UninstallBroadcast("NEWREPSTAUS");
        }

        private void initData(MemberInfo m)
        {
            this.Closing += Window_Closing;
            curvePolyline.Stroke = Brushes.Blue;
            curvePolyline.StrokeThickness = 2;

            px = (this.chartCanvas.Width - yuandian.X - rightM) / 6.0;
            py = (yuandian.Y - topM) / 13.0;

            DrawScale(this.chartCanvas, Color.FromRgb(0xd9, 0x4f, 0x54),Config.limitHz);
            DrawPoint(this.chartCanvas, pointEllipses);
            DrawCurve(this.chartCanvas);

            DrawScale(this.chartCanvas2, Color.FromRgb(0x55, 0xa4, 0xdd), Config.limitHz);
            // DrawPoint(this.chartCanvas2, pointEllipses2);
            // DrawCurve(this.chartCanvas2);

            TestWindowViewModel model = new TestWindowViewModel();

            model.TestMember = m;
            this.DataContext = model;


            model.TestItemEvent += UpdateTestItem;
            model.TestModemEvent += UpdateTestMode;
            PlayButton.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(Button_MouseDown), true);
            PlayButton.AddHandler(Button.MouseUpEvent, new RoutedEventHandler(Button_MouseUp), true);
            // NormalOnButton.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(CheckBox_MouseDown), true);

            TalkButton.AddHandler(Button.MouseDownEvent, new RoutedEventHandler(TalkButton_MouseDown), true);
            TalkButton.AddHandler(Button.MouseUpEvent, new RoutedEventHandler(TalkButton_MouseUp), true);

            DMSkin.Core.Broadcast.RegisterBroadcast<string>("NEWTESTDATA", (obj) =>
            {
                // this.RspStatus.Background = new SolidColorBrush( Color.FromRgb(0xff, 0xff, 0));
            });

            DMSkin.Core.Broadcast.RegisterBroadcast<string>("CLOSEWINDOW", (obj) =>
            {
                //TestWindowViewModel mo = DataContext as TestWindowViewModel;

                //mo.Dispose();
                this.tishiquit = false;
                this.Close();
            });
       
            DMSkin.Core.Broadcast.RegisterBroadcast<byte[]>("NEWREPSTAUS", (obj) =>
            {

                ThreadPool.QueueUserWorkItem(delegate
                {
                    SynchronizationContext.SetSynchronizationContext(new
                        DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                    SynchronizationContext.Current.Post(pl =>
                    {
                        byte[] dataBuffer = obj;


                        int value = dataBuffer[2];

                        if (value == 1)
                        {
                            this.RspStatus.Background = new SolidColorBrush(Color.FromRgb(0, 0xff, 0));
                        }
                        else
                        {
                            this.RspStatus.Background = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
                        }

                        TestWindowViewModel vm = this.DataContext as TestWindowViewModel;

                        //vm.doResponseOK(dataBuffer);
                    }, null);
                });



            });
        }
        private void UpdateTestMode(Dictionary<int, int> limitHz, Dictionary<int, TestItem> leftlist, Dictionary<int, TestItem> rightlist,bool isright)
        {
         
            

            ThreadPool.QueueUserWorkItem(delegate
            {
                SynchronizationContext.SetSynchronizationContext(new
                    DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                SynchronizationContext.Current.Post(pl =>
                {
                    this.chartCanvas.Children.Clear();
                    this.chartCanvas2.Children.Clear();
                    curvePolyline.Stroke = Brushes.Blue;
            curvePolyline.StrokeThickness = 2;

            px = (this.chartCanvas.Width - yuandian.X - rightM) / 6.0;
            py = (yuandian.Y - topM) / 13.0;

            DrawScale(this.chartCanvas, Color.FromRgb(0xd9, 0x4f, 0x54), limitHz);
            DrawPoint(this.chartCanvas, pointEllipses);
            DrawCurve(this.chartCanvas);

            DrawScale(this.chartCanvas2, Color.FromRgb(0x55, 0xa4, 0xdd), limitHz);
                    DrawPoint(this.chartCanvas2, pointEllipses2);
                    DrawCurve(this.chartCanvas2);


                    TestWindowViewModel m = DataContext as TestWindowViewModel;
                    if (isright)
                    {
                        this.UpdateTestItems(leftlist, false);
                        this.UpdateTestItems(rightlist, true);
                    }
                    else
                    {
                        this.UpdateTestItems(rightlist, true);
                        this.UpdateTestItems(leftlist, false);


                    }


                    if (isright)
                    {
                        this.UpdateTestItems(m.leftBcResult, false,1,m.displayoption.IsLinkBc?1:0);
                        this.UpdateTestItems(m.rightBcResult, true,1, m.displayoption.IsLinkBc ? 1 : 0);
                    }
                    else
                    {
                        this.UpdateTestItems(m.rightBcResult, true,1, m.displayoption.IsLinkBc ? 1 : 0);
                        this.UpdateTestItems(m.leftBcResult, false,1, m.displayoption.IsLinkBc ? 1 : 0);


                    }

                }, null);
     

            });
        }

        private void UpdateTestItems(Dictionary<int, TestItem> list, bool isRight, int mmtype = 0, int bcneedlink = 0)
        {
            if(mmtype == 0)
            {
                if (isRight)
                {
                    foreach (Shape dataEllipse in pointEllipses)
                    {
                        this.chartCanvas.Children.Remove(dataEllipse);
                    }
                    foreach (Shape dataEllipse in pointEllipses3)
                    {
                        if (this.chartCanvas.Children.Contains(dataEllipse))
                            this.chartCanvas.Children.Remove(dataEllipse);
                        else
                            this.chartCanvas2.Children.Remove(dataEllipse);
                    }

                    TestWindowViewModel vm = DataContext as TestWindowViewModel;
                    {
                        Line x_scale = new Line();
                        x_scale.StrokeEndLineCap = PenLineCap.Triangle;
                        x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));
                        x_scale.StrokeThickness = 0.3;
                        x_scale.X1 = yuandian.X + hzsPxValue[vm.FrequencyValue] * (this.chartCanvas.Width - yuandian.X - rightM) / 6.0;
                        x_scale.X2 = x_scale.X1;    //在x轴上的刻度线，起点和终点相同

                        x_scale.Y1 = yuandian.Y;           //与原点坐标的y=280，相同 
                        x_scale.Y2 = topM;

                        this.chartCanvas.Children.Add(x_scale);
                        pointEllipses3.Add(x_scale);

                        Line y_scale = new Line();
                        y_scale.StrokeEndLineCap = PenLineCap.Triangle;
                        y_scale.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));

                        y_scale.X1 = yuandian.X;            //原点x=40，在y轴上的刻度线的起点与原点相同
                        y_scale.StrokeThickness = 0.3;

                        y_scale.X2 = this.chartCanvas.Width - rightM;
                        y_scale.Y1 = topM + (vm.ToneDBValue + 10) / 10.0 * ((yuandian.Y - topM) / 13.0);  //每10px作一个刻度 
                        y_scale.Y2 = y_scale.Y1;    //起点和终点y坐标相同 
                        this.chartCanvas.Children.Add(y_scale);
                        pointEllipses3.Add(y_scale);


                        if (vm.IsMaskingOn)
                        {
                            Ellipse dataEllipse = new Ellipse();
                            // dataEllipse.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
                            dataEllipse.Stroke = new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88));//灰色
                            dataEllipse.Width = 12;
                            dataEllipse.Height = 12;
                            Canvas.SetTop(dataEllipse, topM + (10 + vm.MaskDBvalue) / 10.0 * py - 6);
                            Canvas.SetLeft(dataEllipse, yuandian.X + hzsPxValue[vm.FrequencyValue] * px - 6);
                            this.chartCanvas2.Children.Add(dataEllipse);
                            pointEllipses3.Add(dataEllipse);
                        }
                    }

                    TestItem lastitem = null;
                    for (int i = 0; i < this.hzsint.Count(); i++)
                    {
                        //(40,280)原点坐标,上面空45，右边空80
                        // this.chartCanvas.Children.Clear();
                        if (list.ContainsKey(this.hzsint[i]))
                        {
                            TestItem item = list[this.hzsint[i]];


                            if (item.Mask == true)
                            {

                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                  topM + (10 + item.Db) / 10.0 * py,
                                  item.MarkType != 0 ? item.MarkType : 10,
                                  true,
                                  this.chartCanvas,
                                  pointEllipses);

                            }
                            else
                            {
                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                   topM + (10 + item.Db) / 10.0 * py,
                   item.MarkType != 0 ? item.MarkType : 1,
                   true,
                   this.chartCanvas,
                   pointEllipses);
                            }
                        





                            if (item.IsUserResp != true)
                            {
                                TLBIcon.DrawNoRespIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                            topM + (10 + item.Db) / 10.0 * py,
                                            isRight,
                                             this.chartCanvas,
                                            pointEllipses);
                            }


                            if (lastitem != null)
                            {
                                Line line = new Line();
                                line.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));

                                line.Y1 = topM + (10 + lastitem.Db) / 10.0 * py;
                                line.X1 = yuandian.X + hzsPxValue[lastitem.Hz] * px;
                                line.Y2 = topM + (10 + item.Db) / 10.0 * py;
                                line.X2 = yuandian.X + hzsPxValue[item.Hz] * px;
                                line.StrokeThickness = 1;
                                this.chartCanvas.Children.Add(line);
                                pointEllipses.Add(line);

                            }


                            lastitem = item;



                        }

                    }

                }
                else
                {
                    foreach (Shape dataEllipse in pointEllipses2)
                    {
                        this.chartCanvas2.Children.Remove(dataEllipse);
                    }
                    foreach (Shape dataEllipse in pointEllipses3)
                    {
                        if (this.chartCanvas2.Children.Contains(dataEllipse))
                            this.chartCanvas2.Children.Remove(dataEllipse);
                        else
                            this.chartCanvas.Children.Remove(dataEllipse);
                    }


                    TestWindowViewModel vm = DataContext as TestWindowViewModel;
                    {
                        //+字线
                        {
                            Line x_scale = new Line();
                            x_scale.StrokeEndLineCap = PenLineCap.Triangle;
                            x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0x00, 0, 0xff));
                            x_scale.StrokeThickness = 0.3;
                            x_scale.X1 = yuandian.X + hzsPxValue[vm.FrequencyValue] * (this.chartCanvas2.Width - yuandian.X - rightM) / 6.0;
                            x_scale.X2 = x_scale.X1;    //在x轴上的刻度线，起点和终点相同

                            x_scale.Y1 = yuandian.Y;           //与原点坐标的y=280，相同 
                            x_scale.Y2 = topM;

                            this.chartCanvas2.Children.Add(x_scale);
                            pointEllipses3.Add(x_scale);

                            Line y_scale = new Line();
                            y_scale.StrokeEndLineCap = PenLineCap.Triangle;
                            y_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));

                            y_scale.X1 = yuandian.X;            //原点x=40，在y轴上的刻度线的起点与原点相同
                            y_scale.StrokeThickness = 0.3;

                            y_scale.X2 = this.chartCanvas.Width - rightM;
                            y_scale.Y1 = topM + (vm.ToneDBValue + 10) / 10.0 * ((yuandian.Y - topM) / 13.0);  //每10px作一个刻度 
                            y_scale.Y2 = y_scale.Y1;    //起点和终点y坐标相同 
                            this.chartCanvas2.Children.Add(y_scale);
                            pointEllipses3.Add(y_scale);
                        }

                        if (vm.IsMaskingOn)
                        {
                            Ellipse dataEllipse = new Ellipse();
                            // dataEllipse.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
                            dataEllipse.Stroke = new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88));//灰色
                            dataEllipse.Width = 12;
                            dataEllipse.Height = 12;
                            Canvas.SetTop(dataEllipse, topM + (10 + vm.MaskDBvalue) / 10.0 * py - 6);
                            Canvas.SetLeft(dataEllipse, yuandian.X + hzsPxValue[vm.FrequencyValue] * px - 6);
                            this.chartCanvas.Children.Add(dataEllipse);
                            pointEllipses3.Add(dataEllipse);
                        }



                    }


                    TestItem lastitem = null;
                    for (int i = 0; i < this.hzsint.Count(); i++)
                    {
                        //(40,280)原点坐标,上面空45，右边空80
                        // this.chartCanvas.Children.Clear();
                        if (list.ContainsKey(this.hzsint[i]))
                        {
                            TestItem item = list[this.hzsint[i]];

                            if (item.IsUserResp != true)
                            {
                                TLBIcon.DrawNoRespIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                       topM + (10 + item.Db) / 10.0 * py,
                                       isRight,
                                        this.chartCanvas2,
                                       pointEllipses2);
                            }


                            if (item.Mask == true)
                            {
                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                topM + (10 + item.Db) / 10.0 * py,
                                item.MarkType != 0 ? item.MarkType : 9,
                                false,
                                this.chartCanvas2,
                                pointEllipses2);
                            }
                            else
                            {
                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                topM + (10 + item.Db) / 10.0 * py,
                item.MarkType != 0 ? item.MarkType : 2,
                false,
                this.chartCanvas2,
                pointEllipses2);
                            }



                            if (lastitem != null)
                            {
                                Line line = new Line();
                                line.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));

                                line.Y1 = topM + (10 + lastitem.Db) / 10.0 * py;
                                line.X1 = yuandian.X + hzsPxValue[lastitem.Hz] * px;
                                line.Y2 = topM + (10 + item.Db) / 10.0 * py;
                                line.X2 = yuandian.X + hzsPxValue[item.Hz] * px;
                                line.StrokeThickness = 1;


                                this.chartCanvas2.Children.Add(line);
                                pointEllipses2.Add(line);

                            }

                            lastitem = item;



                        }

                    }
                }
            }
            else if(mmtype == 1)
            {
                if (isRight)
                {
                    foreach (Shape dataEllipse in pointBcEllipses)
                    {
                        this.chartCanvas.Children.Remove(dataEllipse);
                    }
                    foreach (Shape dataEllipse in pointEllipses3)
                    {
                        if (this.chartCanvas.Children.Contains(dataEllipse))
                            this.chartCanvas.Children.Remove(dataEllipse);
                        else
                            this.chartCanvas2.Children.Remove(dataEllipse);
                    }

                    TestWindowViewModel vm = DataContext as TestWindowViewModel;
                    {
                        Line x_scale = new Line();
                        x_scale.StrokeEndLineCap = PenLineCap.Triangle;
                        x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));
                        x_scale.StrokeThickness = 0.3;
                        x_scale.X1 = yuandian.X + hzsPxValue[vm.FrequencyValue] * (this.chartCanvas.Width - yuandian.X - rightM) / 6.0;
                        x_scale.X2 = x_scale.X1;    //在x轴上的刻度线，起点和终点相同

                        x_scale.Y1 = yuandian.Y;           //与原点坐标的y=280，相同 
                        x_scale.Y2 = topM;

                        this.chartCanvas.Children.Add(x_scale);
                        pointEllipses3.Add(x_scale);

                        Line y_scale = new Line();
                        y_scale.StrokeEndLineCap = PenLineCap.Triangle;
                        y_scale.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));

                        y_scale.X1 = yuandian.X;            //原点x=40，在y轴上的刻度线的起点与原点相同
                        y_scale.StrokeThickness = 0.3;

                        y_scale.X2 = this.chartCanvas.Width - rightM;
                        y_scale.Y1 = topM + (vm.ToneDBValue + 10) / 10.0 * ((yuandian.Y - topM) / 13.0);  //每10px作一个刻度 
                        y_scale.Y2 = y_scale.Y1;    //起点和终点y坐标相同 
                        this.chartCanvas.Children.Add(y_scale);
                        pointEllipses3.Add(y_scale);


                        if (vm.IsMaskingOn)
                        {
                            Ellipse dataEllipse = new Ellipse();
                            // dataEllipse.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
                            dataEllipse.Stroke = new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88));//灰色
                            dataEllipse.Width = 12;
                            dataEllipse.Height = 12;
                            Canvas.SetTop(dataEllipse, topM + (10 + vm.MaskDBvalue) / 10.0 * py - 6);
                            Canvas.SetLeft(dataEllipse, yuandian.X + hzsPxValue[vm.FrequencyValue] * px - 6);
                            this.chartCanvas2.Children.Add(dataEllipse);
                            pointEllipses3.Add(dataEllipse);
                        }
                    }

                    TestItem lastitem = null;
                    for (int i = 0; i < this.hzsint.Count(); i++)
                    {
                        //(40,280)原点坐标,上面空45，右边空80
                        // this.chartCanvas.Children.Clear();
                        if (list.ContainsKey(this.hzsint[i]))
                        {
                            TestItem item = list[this.hzsint[i]];


                            if (item.Mask == true)
                            {
                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                      topM + (10 + item.Db) / 10.0 * py,
                                      item.MarkType != 0 ? item.MarkType : 6,
                                      isRight,
                                      this.chartCanvas,
                                      pointBcEllipses);


                            }
                            else
                            {
                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                            topM + (10 + item.Db) / 10.0 * py,
                                            item.MarkType != 0 ? item.MarkType : 4,
                                            isRight,
                                            this.chartCanvas,
                                            pointBcEllipses);

                            }





                            if (item.IsUserResp != true)
                            {
                                TLBIcon.DrawNoRespIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                   topM + (10 + item.Db) / 10.0 * py,
                                   isRight,
                                    this.chartCanvas,
                                   pointBcEllipses);
                            }

                            //骨导默认不连线
                            if (lastitem != null && bcneedlink == 1)
                            {
                                //Line line = new Line();
                                //line.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));

                                //line.Y1 = topM + (10 + lastitem.Db) / 10.0 * py;
                                //line.X1 = yuandian.X + hzsPxValue[lastitem.Hz] * px;
                                //line.Y2 = topM + (10 + item.Db) / 10.0 * py;
                                //line.X2 = yuandian.X + hzsPxValue[item.Hz] * px;
                                //line.StrokeThickness = 1;
                                //this.chartCanvas.Children.Add(line);
                                //pointBcEllipses.Add(line);

                                Polyline x_scale = new Polyline();
                                x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));
                                x_scale.StrokeDashArray.Add(10);
                                x_scale.StrokeDashArray.Add(20);
                     ;
                                x_scale.StrokeThickness = 0.5;
                                x_scale.Points.Add(new Point(yuandian.X + hzsPxValue[lastitem.Hz] * px, topM + (10 + lastitem.Db) / 10.0 * py));
                                x_scale.Points.Add(new Point(yuandian.X + hzsPxValue[item.Hz] * px, topM + (10 + item.Db) / 10.0 * py));    
                           

                                this.chartCanvas.Children.Add(x_scale);
                                pointBcEllipses.Add(x_scale);
                            }


                            lastitem = item;



                        }

                    }

                }
                else
                {
                    foreach (Shape dataEllipse in pointBcEllipses2)
                    {
                        this.chartCanvas2.Children.Remove(dataEllipse);
                    }
                    foreach (Shape dataEllipse in pointEllipses3)
                    {
                        if (this.chartCanvas2.Children.Contains(dataEllipse))
                            this.chartCanvas2.Children.Remove(dataEllipse);
                        else
                            this.chartCanvas.Children.Remove(dataEllipse);
                    }


                    TestWindowViewModel vm = DataContext as TestWindowViewModel;
                    {
                        //+字线
                        {
                            Line x_scale = new Line();
                            x_scale.StrokeEndLineCap = PenLineCap.Triangle;
                            x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0x00, 0, 0xff));
                            x_scale.StrokeThickness = 0.3;
                            x_scale.X1 = yuandian.X + hzsPxValue[vm.FrequencyValue] * (this.chartCanvas2.Width - yuandian.X - rightM) / 6.0;
                            x_scale.X2 = x_scale.X1;    //在x轴上的刻度线，起点和终点相同

                            x_scale.Y1 = yuandian.Y;           //与原点坐标的y=280，相同 
                            x_scale.Y2 = topM;

                            this.chartCanvas2.Children.Add(x_scale);
                            pointEllipses3.Add(x_scale);

                            Line y_scale = new Line();
                            y_scale.StrokeEndLineCap = PenLineCap.Triangle;
                            y_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));

                            y_scale.X1 = yuandian.X;            //原点x=40，在y轴上的刻度线的起点与原点相同
                            y_scale.StrokeThickness = 0.3;

                            y_scale.X2 = this.chartCanvas.Width - rightM;
                            y_scale.Y1 = topM + (vm.ToneDBValue + 10) / 10.0 * ((yuandian.Y - topM) / 13.0);  //每10px作一个刻度 
                            y_scale.Y2 = y_scale.Y1;    //起点和终点y坐标相同 
                            this.chartCanvas2.Children.Add(y_scale);
                            pointEllipses3.Add(y_scale);
                        }

                        if (vm.IsMaskingOn)
                        {
                            Ellipse dataEllipse = new Ellipse();
                            // dataEllipse.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
                            dataEllipse.Stroke = new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88));//灰色
                            dataEllipse.Width = 12;
                            dataEllipse.Height = 12;
                            Canvas.SetTop(dataEllipse, topM + (10 + vm.MaskDBvalue) / 10.0 * py - 6);
                            Canvas.SetLeft(dataEllipse, yuandian.X + hzsPxValue[vm.FrequencyValue] * px - 6);
                            this.chartCanvas.Children.Add(dataEllipse);
                            pointEllipses3.Add(dataEllipse);
                        }



                    }


                    TestItem lastitem = null;
                    for (int i = 0; i < this.hzsint.Count(); i++)
                    {
                        //(40,280)原点坐标,上面空45，右边空80
                        // this.chartCanvas.Children.Clear();
                        if (list.ContainsKey(this.hzsint[i]))
                        {
                            TestItem item = list[this.hzsint[i]];

                            if (item.IsUserResp != true)
                            {
                                TLBIcon.DrawNoRespIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                    topM + (10 + item.Db) / 10.0 * py,
                                    isRight,
                                     this.chartCanvas2,
                                    pointBcEllipses2);
                            }


                            if (item.Mask == true)
                            {
                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                      topM + (10 + item.Db) / 10.0 * py,
                                      item.MarkType != 0 ? item.MarkType : 5,
                                      isRight,
                                      this.chartCanvas2,
                                      pointBcEllipses2);
                            }
                            else
                            {

                                TLBIcon.DrawIconByType(yuandian.X + hzsPxValue[item.Hz] * px,
                                            topM + (10 + item.Db) / 10.0 * py,
                                            item.MarkType != 0 ? item.MarkType : 3,
                                            isRight,
                                            this.chartCanvas2,
                                            pointBcEllipses2);
                            }



                            if (lastitem != null && bcneedlink == 1)
                            {
                                //Line line = new Line();
                                //line.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));

                                //line.Y1 = topM + (10 + lastitem.Db) / 10.0 * py;
                                //line.X1 = yuandian.X + hzsPxValue[lastitem.Hz] * px;
                                //line.Y2 = topM + (10 + item.Db) / 10.0 * py;
                                //line.X2 = yuandian.X + hzsPxValue[item.Hz] * px;
                                //line.StrokeThickness = 1;


                                //this.chartCanvas2.Children.Add(line);
                                //pointBcEllipses2.Add(line);


                                Polyline x_scale = new Polyline();
                                x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
                                x_scale.StrokeDashArray.Add(10);
                                x_scale.StrokeDashArray.Add(20);
                                ;
                                x_scale.StrokeThickness = 0.5;
                                x_scale.Points.Add(new Point(yuandian.X + hzsPxValue[lastitem.Hz] * px, topM + (10 + lastitem.Db) / 10.0 * py));
                                x_scale.Points.Add(new Point(yuandian.X + hzsPxValue[item.Hz] * px, topM + (10 + item.Db) / 10.0 * py));


                                this.chartCanvas2.Children.Add(x_scale);
                                pointBcEllipses2.Add(x_scale);

                            }

                            lastitem = item;



                        }

                    }
                }
            }
  

        }

        private void UpdateTestItem(Dictionary<int, TestItem> list, bool isRight, int mmtype = 0, int bcneedlink = 0)
        {

            ThreadPool.QueueUserWorkItem(delegate
            {
                SynchronizationContext.SetSynchronizationContext(new
                    DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                SynchronizationContext.Current.Post(pl =>
                {
                    this.UpdateTestItems(list, isRight, mmtype, bcneedlink);

                }, null);
            });
        }
        /// <summary>
        /// 作出箭头
        /// </summary>
        private void DrawArrow()
        {
            Path x_axisArrow = new Path();//x轴箭头
            Path y_axisArrow = new Path();//y轴箭头

            x_axisArrow.Fill = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));
            y_axisArrow.Fill = new SolidColorBrush(Color.FromRgb(0xff, 0, 0));

            PathFigure x_axisFigure = new PathFigure();
            x_axisFigure.IsClosed = true;
            x_axisFigure.StartPoint = new Point(480, 276);                          //路径的起点
            x_axisFigure.Segments.Add(new LineSegment(new Point(480, 284), false)); //第2个点
            x_axisFigure.Segments.Add(new LineSegment(new Point(490, 280), false)); //第3个点

            PathFigure y_axisFigure = new PathFigure();
            y_axisFigure.IsClosed = true;
            y_axisFigure.StartPoint = new Point(36, 30);                          //路径的起点
            y_axisFigure.Segments.Add(new LineSegment(new Point(44, 30), false)); //第2个点
            y_axisFigure.Segments.Add(new LineSegment(new Point(40, 20), false)); //第3个点

            PathGeometry x_axisGeometry = new PathGeometry();
            PathGeometry y_axisGeometry = new PathGeometry();

            x_axisGeometry.Figures.Add(x_axisFigure);
            y_axisGeometry.Figures.Add(y_axisFigure);

            x_axisArrow.Data = x_axisGeometry;
            y_axisArrow.Data = y_axisGeometry;

            this.chartCanvas.Children.Add(x_axisArrow);
            this.chartCanvas.Children.Add(y_axisArrow);
        }
        /// <summary>
        /// 作出x轴和y轴的标尺
        /// </summary>
        private void DrawScale(Canvas canvas,Color color, Dictionary<int, int> limit)
        {

            foreach(int hz in hzsint)
            {//{ 125, 250, 500,750, 1000,1500, 2000,3000, 4000,6000, 8000 };
                int value = limit[hz];

                Rectangle rect = new Rectangle();
                //(40 + px * hzsint.IndexOf(hz), 280, px, py * (120 - value));
                rect.Fill = new SolidColorBrush(color);
                double index = hzsPxValue[hz];


                rect.Height = py * (120 - value)/10.0;
               
                if(index == 0 )
                {
                    rect.Width = px/2;
                    Canvas.SetLeft(rect, yuandian.X );
                }
                else if (index == 5.5)
                {
                    rect.Width = px / 2;
                    Canvas.SetLeft(rect, yuandian.X + px * index - px / 4);
                }
                else if (index == 6)
                {
                    rect.Width = px / 4;
                    Canvas.SetLeft(rect, yuandian.X + px * index - px / 4);
                }
                else
                {
                    rect.Width = px;
                    Canvas.SetLeft(rect, yuandian.X + px * index-px/2);
                }
                
                Canvas.SetTop(rect,yuandian.Y-rect.Height );
                canvas.Children.Add(rect);

            }


            //(40,280)原点坐标,上面空45，右边空80

            //"1500", "3000", "6000",

            for (int i = 0; i < 4; i += 1)//作480个刻度，因为当前x轴长 480px，每10px作一个小刻度，还预留了一些小空间
            {
                //原点 O=(40,280),s

                Polyline x_scale = new Polyline();
                x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0));
                x_scale.StrokeDashArray.Add(10);
                x_scale.StrokeDashArray.Add(20);
                /// Line x_scale = new Line();
                //x_scale.StrokeEndLineCap = PenLineCap.Triangle;
                //x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0));
                x_scale.StrokeThickness = 0.1;
                x_scale.Points.Add(new Point( yuandian.X +(2.5+ i) * (canvas.Width - yuandian.X - rightM) / 6.0, yuandian.Y));
                x_scale.Points.Add(new Point( yuandian.X + (2.5 + i) * (canvas.Width - yuandian.X - rightM) / 6.0, topM));    //在x轴上的刻度线，起点和终点相同

                //x_scale.Y1 = yuandian.Y;           //与原点坐标的y=280，相同 
                //x_scale.Y2 = topM;


                canvas.Children.Add(x_scale);

            }

            for (int i = 0; i < 7; i += 1)//作480个刻度，因为当前x轴长 480px，每10px作一个小刻度，还预留了一些小空间
            {
                //原点 O=(40,280),s
                Line x_scale = new Line();
                x_scale.StrokeEndLineCap = PenLineCap.Triangle;
                x_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0));
                x_scale.StrokeThickness = 0.1;
                x_scale.X1 = yuandian.X + i * (canvas.Width-yuandian.X-rightM)/6.0;   
                x_scale.X2 = x_scale.X1;    //在x轴上的刻度线，起点和终点相同

                x_scale.Y1 = yuandian.Y;           //与原点坐标的y=280，相同 
                x_scale.Y2 = topM;


                canvas.Children.Add(x_scale);

             
                {
                    TextBlock x_ScaleLabel = new TextBlock();
             
                    x_ScaleLabel.TextAlignment = TextAlignment.Left;
                    x_ScaleLabel.Width = (canvas.Width - yuandian.X - rightM) / 6.0;
                    x_ScaleLabel.FontSize = 12;
                    x_ScaleLabel.Text = hzs[i]; ;//只给大刻度添加标签，每50px添加一个标签

                    Canvas.SetLeft(x_ScaleLabel, yuandian.X + i * (canvas.Width - yuandian.X - rightM) / 6.0 - 12);//40是原点的坐标，-12是为了让标签看的位置剧中一点
                    Canvas.SetTop(x_ScaleLabel, yuandian.Y + 10);//让标签字往下移一点

                    canvas.Children.Add(x_ScaleLabel);
        
                }


            }

            for (int i = 0; i < 14; i += 1)//由于y轴短一些，所以在此作出判断，只作25个刻度
            {
                //作出Y轴的刻度
                Line y_scale = new Line();
                y_scale.StrokeEndLineCap = PenLineCap.Triangle;
                y_scale.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0));

                y_scale.X1 = yuandian.X;            //原点x=40，在y轴上的刻度线的起点与原点相同
                y_scale.StrokeThickness = 0.1;

                y_scale.X2 = canvas.Width-rightM;
                y_scale.Y1 = topM + i * ((yuandian.Y- topM)/13.0);  //每10px作一个刻度 
                y_scale.Y2 = y_scale.Y1;    //起点和终点y坐标相同 
                canvas.Children.Add(y_scale);

                if(i%2 == 1)
                {
                    TextBlock y_ScaleLabel = new TextBlock();
                    y_ScaleLabel.TextAlignment = TextAlignment.Center;
                    y_ScaleLabel.Width = 30;
                    y_ScaleLabel.FontSize = 12;
                    y_ScaleLabel.Text = (-10 + i * 10).ToString();
                    Canvas.SetLeft(y_ScaleLabel, yuandian.X - 30);              //-25px是字体大小的偏移
                    Canvas.SetTop(y_ScaleLabel, topM + i * ((yuandian.Y - topM) / 13.0) - 10);  //280px是原点的坐标，同样-6是为了让标签不要上坐标轴叠上

                    canvas.Children.Add(y_ScaleLabel);
                }
               
            }
            {
                TextBlock x_ScaleLabel = new TextBlock();
                x_ScaleLabel.Text = "Hz"; ;//只给大刻度添加标签，每50px添加一个标签

                Canvas.SetLeft(x_ScaleLabel, canvas.Width-rightM + 12);//40是原点的坐标，-12是为了让标签看的位置剧中一点
                Canvas.SetTop(x_ScaleLabel, yuandian.Y + 10);//让标签字往下移一点

                canvas.Children.Add(x_ScaleLabel);

                TextBlock y_ScaleLabel = new TextBlock();

                y_ScaleLabel.Text = "dBHL";
                Canvas.SetLeft(y_ScaleLabel, yuandian.X - 30);
                Canvas.SetTop(y_ScaleLabel, topM-30);

                canvas.Children.Add(y_ScaleLabel);
            }

        }
        /// <summary>
        /// 添加刻度标签
        /// </summary>
        //private void DrawScaleLabel(Canvas canvas)
        //{
        //    for (int i = 1; i < 7; i++)//7 个标签，一共
        //    {
        //        TextBlock x_ScaleLabel = new TextBlock();
        //        TextBlock y_ScaleLabel = new TextBlock();

        //        x_ScaleLabel.Text = (i * 50).ToString();//只给大刻度添加标签，每50px添加一个标签

        //        Canvas.SetLeft(x_ScaleLabel, 40 + 5 * 10 * i - 12);//40是原点的坐标，-12是为了让标签看的位置剧中一点
        //        Canvas.SetTop(x_ScaleLabel, 280 + 2);//让标签字往下移一点

        //        y_ScaleLabel.Text = (i * 50).ToString();
        //        Canvas.SetLeft(y_ScaleLabel, 40 - 25);              //-25px是字体大小的偏移
        //        Canvas.SetTop(y_ScaleLabel, 280 - 5 * 10 * i - 6);  //280px是原点的坐标，同样-6是为了让标签不要上坐标轴叠上

        //        canvas.Children.Add(x_ScaleLabel);
        //        canvas.Children.Add(y_ScaleLabel);
        //    }
        //}

        private void DrawPoint(Canvas canvas, List<Shape> list)
        {
            //随机生成8个点

            
            //Random rPoint = new Random();
            //for (int i = 0; i < 7; i++)
            //{
            //    int x_point = i * 60;
            //    int y_point = rPoint.Next(250);
            //    dataPoints.Add(new Point(x_point, y_point));
            //}

            //for (int i = 0; i < dataPoints.Count; i++)
            //{
            //    Ellipse dataEllipse = new Ellipse();
            //    dataEllipse.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
            //    dataEllipse.Width = 8;
            //    dataEllipse.Height = 8;

            //    list.Add(dataEllipse);

            //    Canvas.SetLeft(list[i], 40 + dataPoints[i].X - 4);//-4是为了补偿圆点的大小，到精确的位置
            //    Canvas.SetTop(list[i], 280 - dataPoints[i].Y - 4);
            //    //将数据点在画布中的位置保存下来
            //    coordinatePoints.Add(new Point(40 + dataPoints[i].X, 280 - dataPoints[i].Y));
            //    canvas.Children.Add(list[i]);
            //}
        }

        private void DrawCurve(Canvas canvas)
        {
            //curvePolyline.Points = coordinatePoints;
            //canvas.Children.Add(curvePolyline);
        }
        private void AddCurvePoint(Point dataPoint)
        {
          
            dataPoints.Add(dataPoint);
                Ellipse dataEllipse = new Ellipse();
                dataEllipse.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0xff));
               dataEllipse.Width = 8;
                dataEllipse.Height = 8;

            Random rPoint = new Random();
            //    Canvas.SetTop(list[i], 280 - dataPoints[i].Y - 4);
            //    //将数据点在画布中的位置保存下来
            coordinatePoints.Add(new Point(50* rPoint.Next(7), dataPoint.Y));
                this.chartCanvas.Children.Add(dataEllipse);         //  int i = dataPoints.Count;

            //Random rPoint = new Random();
            // int x_point = i * 60;
            // int y_point = rPoint.Next(250);
            //  dataPoints.Add(new Point(x_point, y_point));
            // for (int i = 0; i < dataPoints.Count; i++)
            //{
            //每一个点的X数据都要向左移动50px
            //    dataPoints[i] = new Point(dataPoints[i].X - 50, dataPoints[i].Y);
            //    coordinatePoints[i] = new Point(40 + dataPoints[i].X, 280 - dataPoints[i].Y);

            // Canvas.SetLeft(pointEllipses[i], 40 + dataPoints[i].X - 4);//-4是为了补偿圆点的大小，到精确的位置
            //  Canvas.SetTop(pointEllipses[i], 280 - dataPoints[i].Y - 4);
            // }
        }

        private void chartCanvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //随机生成Y坐标
            //Point dataPoint = new Point((new Random()).Next(250), (new Random()).Next(250));

            //AddCurvePoint(dataPoint);
        }

        private void Button_MouseDown(object sender, EventArgs e)
        {
            TestWindowViewModel model = this.DataContext as TestWindowViewModel;

            if(model.IsNormalOn)
            {
      
                model.stopPlay();
            }
            else
            {
    
                model.startPlay();
            }

            
            
        }

        private void Button_MouseUp(object sender, EventArgs e)
        {
            TestWindowViewModel model = this.DataContext as TestWindowViewModel;

            if (model.IsNormalOn)
            {
              
                model.startPlay();
            }
            else
            {
             
                model.stopPlay();
            }
           
        }

        //private void CheckBox_MouseDown(object sender, EventArgs e)
        //{
        //    TestWindowViewModel model = this.DataContext as TestWindowViewModel;

        //    if (model.IsNormalOn)
        //    {
        //        PlayButton.Content = "压下暂停";
        //        model.startPlay();
        //    }
        //    else
        //    {
        //        PlayButton.Content = "压下播放";
        //        model.stopPlay();
        //    }
        //}
        
 private void TalkButton_MouseDown(object sender, EventArgs e)
        {
            TestWindowViewModel model = this.DataContext as TestWindowViewModel;

            model.TalkClick( true);



        }

        private void TalkButton_MouseUp(object sender, EventArgs e)
        {
            TestWindowViewModel model = this.DataContext as TestWindowViewModel;

            model.TalkClick(false);

        }
        


    private void TestWindow_Keydown(object sender, KeyEventArgs e)
    {

            //    left = 23,
            ////
            //// 摘要:
            ////     up arrow 键。
            //up = 24,
            ////
            //// 摘要:
            ////     right arrow 键。
            //right = 25,
            ////
            //// 摘要:
            ////     down arrow 键。
            //down = 26,


            TestWindowViewModel model = this.DataContext as TestWindowViewModel;
            if(e.Key == Key.Up)
            {
                model.downStimulus();
               
            }
            else if (e.Key == Key.Down)
            {
                model.upStimulus();
            }
            else if (e.Key == Key.Left)
            {
                model.downFrequency();
            }
            else if (e.Key == Key.Right)
            {
                model.upFrequency();
            }

            else if (e.Key == Key.Enter)
            {

                if(!model.PlayButtonText.Equals("播放中"))
                {
                    if (model.IsNormalOn)
                    {

                        model.stopPlay();
                    }
                    else
                    {

                        model.startPlay();
                    }
                }
                else
                {
                    if (model.IsNormalOn)
                    {

                        model.startPlay();
                    }
                    else
                    {

                        model.stopPlay();
                    }
                }
  



       


            }

            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.L)
            {

                model.changeToLeft(true);

            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.R)
            {

                model.changeToLeft(false);

            }

            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.M)
            {

                model.IsMaskingOn = !model.IsMaskingOn;

            }

            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.T)
            {

                model.IsTalkOn = !model.IsTalkOn;

            }


            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.A)
            {

                model.MModeType = false;

            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.B)
            {

                model.MModeType = true;

            }
            else if (e.Key == Key.Space)
            {
                   model.saveItem("false");
            }
            else if (e.Key == Key.Back)
            {
                //删除
                model.deleteItem();
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.G)
            {

                model.IsTracking = !model.IsTracking;

            }

            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.N)
            {

                model.IsNormalOn = !model.IsNormalOn;

            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.S)
            {

                model.saveTestResult("false");

            }

            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.Y)
            {

                model.IsMaintainintensity = !model.IsMaintainintensity;

            }

            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.J)
            {

                model.IsAutojump = !model.IsAutojump;

            }

            e.Handled = true;
      
       

             //判断用户的按键是否为Alt+F4
            //  if (e.KeyStates == Keyboard.GetKeyStates(Key.F4) && Keyboard.Modifiers == ModifierKeys.Alt)
            //{
            //if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.C)
            //{
            //    //同时按下了Ctrl + H键（H要最后按，因为判断了此次事件的e.Key）
            //    //修饰键只能按下Ctrl，如果还同时按下了其他修饰键，则不会进入

            //    e.Handled = true;
            //    MessageBox.Show("请输入解锁密码！");
            //}

        }


    }

}